﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace TravelSite.Code
{
    public class BaseDataPage : BasePage
    {
        public string PageName { get; set; }
        protected int DefaultPageSize = 50;

        protected string SortExpression
        {
            get
            {
                if (this.Session[PageName + "_SortExpression"] != null)
                    return this.Session[PageName + "_SortExpression"].ToString();
                else
                    return "";
            }
            set
            {
                //value = "[" + value + "]";
                string result = value + " asc";

                if (!string.IsNullOrEmpty(SortExpression))
                {
                    string[] sortItems = ParseSortExpression();
                    if (sortItems.Length == 2)
                        if (sortItems[0].Equals(value))
                            result = value + " " + (sortItems[1].Equals("asc") ? "desc" : "asc");
                }

                this.Session[PageName + "_SortExpression"] = result;
            }
        }

        protected string[] ParseSortExpression()
        {
            string colName = "";
            string dirName = "";

            if (!string.IsNullOrEmpty(SortExpression))
            {
                int index = SortExpression.LastIndexOf(" ");
                colName = SortExpression.Substring(0, index);
                dirName = SortExpression.Substring(index + 1);
            }

            return new string[] { colName, dirName };

        }

        protected Image GetSortIcon(string dataField)
        {
            Image result = null;
            //dataField = "[" + dataField + "]";
            if (!string.IsNullOrEmpty(SortExpression))
            {
                string[] sortItems = ParseSortExpression();
                if (sortItems.Length == 2)
                    if (sortItems[0].Equals(dataField))
                    {
                        result = new Image();
                        result.CssClass = "sort_icon";
                        if (sortItems[1].Equals("asc"))
                            result.ImageUrl = "~/Images/sort_up.png";
                        else
                            result.ImageUrl = "~/Images/sort_down.png";
                    }
            }

            return result;
        }

        public virtual void LoadData()
        {
        }

        protected void LoadPageSizes(DropDownList ddl)
        {
            string[] data = new string[] { "10", "20", "50", "100", "All" };
            ddl.Items.Clear();
            foreach (string item in data)
            {
                ddl.Items.Add(item);
            }
            ddl.SelectedIndex = Array.IndexOf(data, "50");
        }
    }
}